import React, {useEffect, useRef, useState, useCallback, useMemo} from 'react';
import Btn2 from "../Btn/Btn2";
import {Button} from "antd";

import 'ol/ol.css';
import Map from 'ol/Map';
import XYZ from 'ol/source/XYZ';
import TileLayer from 'ol/layer/Tile';
import View from 'ol/View';
import {Vector as VectorSource} from "ol/source";
import {Vector as VectorLayer} from "ol/layer";
import GeoJSON from "ol/format/GeoJSON";
import Overlay from "ol/Overlay";

import * as echarts from 'echarts';

import axios from "axios";
import "./Map.css"

const MapService = () => {
    const chartRef = useRef(null);
    const [humidityData, setHumidityData] = useState([]);
    const [precipitationData, setPrecipitationData] = useState([]);
    const [isShow, setIsShow] = useState(false);
    const [displayHumidity, setDisplayHumidity] = useState(true);
    const [mapActive, setMapActive] = useState(true);

    const displayEvent = useCallback(() => {
        setDisplayHumidity(prev => !prev);
    }, []);

    // 写一个用来接收子组件的数据
    const weatherDataChange = useCallback((humidityData, precipitationData, t) => {
        setHumidityData(humidityData);
        setPrecipitationData(precipitationData);
        setIsShow(t);
    }, []);

    //获取湿度，降水数据
    const humidityValueList = useMemo(() => humidityData.map(item => item.value * 100), [humidityData]);
    const precipitationValueList = useMemo(() => precipitationData.map(item => item.value), [precipitationData]);

    // 写一个获取小时 的函数
    const getHour = useCallback((data) => {
        return data.map(item => `${new Date(item.datetime).getHours()}时`);
    }, []);

    //渲染表格
    const renderChart = useCallback(() => {
        if (chartRef.current) {
            let myChart = echarts.getInstanceByDom(chartRef.current);
            if (myChart) {
                myChart.dispose();
            }
            myChart = echarts.init(chartRef.current);

            const option = {
                title: {
                    text: displayHumidity ? '未来12小时湿度' : '未来12小时降雨量',
                    left: 'center',
                },
                tooltip: {
                    trigger: 'axis'
                },
                xAxis: {
                    type: 'category',
                    data: getHour(displayHumidity ? humidityData : precipitationData)
                },
                yAxis: {
                    type: 'value',
                    name: displayHumidity ? '湿度（%）' : '降雨量（mm）'
                },
                series: [{
                    data: displayHumidity ? humidityValueList : precipitationValueList,
                    type: 'line',
                    smooth: true,
                    name: displayHumidity ? '湿度（%）' : '降雨量（mm）',
                    areaStyle: {}
                }],
                grid: [
                    {
                        top: '20%',
                        bottom: '15%',
                        right: '3%',
                        left: "6%"
                    }
                ],
            };
            myChart.setOption(option);

            return () => {
                myChart.dispose();
            };
        }
    }, [displayHumidity, getHour, humidityData, precipitationData, humidityValueList, precipitationValueList]);

    // 获取dom，渲染表格
    useEffect(() => {
        if (isShow) {
            renderChart();
        }
    }, [isShow, renderChart]);


    // 地图相关的
    const [lon, setLon] = useState([]);
    const infoRef = useRef(null);

    useEffect(() => {
        const container = infoRef.current;
        const overlay = new Overlay({
            element: container,
            positioning: "center-center",
            autoPan: {
                animation: {
                    duration: 250,
                },
            },
        });

        const token = "fd9b52461875f08212b5446b4eeef167";
        const map = new Map({
            target: 'map',
            layers: [
                new TileLayer({
                    source: new XYZ({
                        url: `https://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${token}`,
                    }),
                }),
                new VectorLayer({
                    source: new VectorSource({
                        url: "https://geo.datav.aliyun.com/areas_v3/bound/320100_full.json",
                        format: new GeoJSON()
                    })
                })
            ],
            overlays: [overlay],
            view: new View({
                projection: "EPSG:4326",
                center: [118.80, 32.06],
                zoom: 10,
            }),
        });

        const handleClick = (e) => {
            console.log(e)
            if (mapActive) {
                overlay.setPosition(e.coordinate);
                container.innerText = e.coordinate;
                setLon(e.coordinate);

                const weatherApi = `/weather-api/v2.6/QxR1YH5GOjqUl8EB/${e.coordinate[0]},${e.coordinate[1]}/hourly?hourlysteps=24`
                axios.get(weatherApi)
                    .then(req => {
                        setIsShow(true);
                        setHumidityData(req.data.result.hourly.humidity);
                        setPrecipitationData(req.data.result.hourly.precipitation);
                    })
                    .catch(error => {
                        console.error('出错了:', error);
                    });
            }
        };

        map.on("singleclick", handleClick);

        return () => {
            map.un("singleclick", handleClick);
            map.setTarget(null);
        };
    }, [mapActive]);

    return (
        <div style={{margin: '0px 0px 0px 10px', width: '98%'}}>
            <Btn2 onClick={weatherDataChange} lon={lon} setMapActive={setMapActive}></Btn2>
            <div id="info" ref={infoRef} ></div>
            <div id="map"></div>

            <div className="chartContent">
                <div  className="chartInnerContentInit" style={{display: isShow ? "none" : "flex"}}>
                    <div>
                        <h1>降水量趋势图</h1>
                        <h1>相对湿度趋势图</h1>
                    </div>
                </div>
                <div className="chartInnerContentShow" style={{display: isShow ? "block" : "none"}}>
                    <div className="chart" ref={chartRef} ></div>
                    <Button className="chartButton" type={"primary"} size="small"
                            onClick={displayEvent}
                    >
                        {displayHumidity ? '切换降雨' : '切换湿度'}
                    </Button>
                </div>
            </div>
        </div>
    );
}

export default MapService;
